const mysql = require('mysql2/promise')
const bcrypt = require('bcrypt')

const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: 'GKL9512357',
  database: 'novel_platform',
  charset: 'utf8mb4'
}

async function restoreQQUser () {
  let connection
  try {
    connection = await mysql.createConnection(dbConfig)

    const email = '1477042095@qq.com'
    const username = 'qq1477042095'
    const nickname = 'QQ用户'
    const password = '123456' // 默认密码，你可以后续修改

    console.log(`🔄 重新创建用户: ${email}`)

    // 检查是否已存在
    const [existingUsers] = await connection.execute(
      'SELECT id FROM users WHERE email = ? OR username = ?',
      [email, username]
    )

    if (existingUsers.length > 0) {
      console.log('⚠️ 用户已存在，删除后重新创建...')
      await connection.execute(
        'DELETE FROM users WHERE email = ? OR username = ?',
        [email, username]
      )
    }

    console.log('🔐 加密密码...')
    const saltRounds = 10
    const passwordHash = await bcrypt.hash(password, saltRounds)

    console.log('👤 创建用户...')
    const [result] = await connection.execute(
      `INSERT INTO users (username, email, nickname, password_hash, role, status, level, coins, is_vip, created_at, updated_at) 
       VALUES (?, ?, ?, ?, 'user', 'active', 1, 100, false, NOW(), NOW())`,
      [username, email, nickname, passwordHash]
    )

    console.log('✅ 用户创建成功！')
    console.log(`📧 邮箱: ${email}`)
    console.log(`🔑 密码: ${password}`)
    console.log(`👤 用户名: ${username}`)
    console.log(`📛 昵称: ${nickname}`)
    console.log(`🛡️ 角色: user`)
    console.log(`🆔 用户ID: ${result.insertId}`)
    console.log(`💰 金币: 100`)

    console.log('\n🔍 验证用户创建...')
    const [verifyUser] = await connection.execute(
      'SELECT * FROM users WHERE email = ?',
      [email]
    )

    if (verifyUser.length > 0) {
      console.log('✅ 验证成功，用户已存在于数据库中')
    } else {
      console.log('❌ 验证失败，用户未找到')
    }
  } catch (error) {
    console.error('❌ 错误:', error.message)
  } finally {
    if (connection) await connection.end()
  }
}

restoreQQUser()
